package top.likeqc.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.likeqc.common.lang.Result;
import top.likeqc.controller.easyexcel.StudentUploadDataListener;
import top.likeqc.controller.easyexcel.TeacherUploadDataListener;
import top.likeqc.controller.easyexcel.UploadData;
import top.likeqc.entity.Student;
import top.likeqc.service.IClassService;
import top.likeqc.service.IGradeService;
import top.likeqc.service.IStudentService;

import java.io.IOException;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-10
 */
@RestController
@RequestMapping("/student")
public class StudentController extends BaseController {

    @Autowired
    IStudentService studentService;

    @Autowired
    IClassService classService;

    @Autowired
    IGradeService gradeService;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @GetMapping()
    // @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String keyStr,
                       Long gradeId,
                       Long classId) {

        QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>().like(StringUtils.isNotBlank(keyStr), "name", keyStr);
        if (gradeId != null) {
            queryWrapper.eq("grade_id", gradeId);
        }
        if (classId != null) {
            queryWrapper.eq("class_id", classId);
        }
        queryWrapper.orderByAsc("number");

        Page<Student> pageData = studentService.page(getPage(), queryWrapper);

        pageData.getRecords().forEach(student -> {
            student.setGrade(gradeService.getById(student.getGradeId()));
            student.setAClass(classService.getById(student.getClassId()));
        });

        return Result.success(pageData);
    }

    /**
     * 新增、修改 学生
     *
     * @param student
     * @return
     */
    @PostMapping()
    // @PreAuthorize("hasAuthority('sys:user:save')")
    public Result edit(@Validated @RequestBody Student student) {
        student = studentService.edit(student);
        return Result.success(student);
    }

    @Transactional
    @DeleteMapping()
    // @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] userIds) {
        studentService.delete(userIds);
        return Result.success("");
    }

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p>
     * 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link TeacherUploadDataListener}
     * <p>
     * 3. 直接读即可
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file, Long gradeId, Long classId) throws IOException {
        EasyExcel.read(file.getInputStream(), Student.class,
            new StudentUploadDataListener(studentService, gradeId, classId)).sheet().doRead();
        return Result.success("");
    }

}
